<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: GetCircle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\note;

use app\api\model\dao\Note;
use app\api\model\dao\NoteReply;
use app\api\model\dao\NoteReplyPraise;
use app\api\model\dao\NoteReplyReply;
use app\api\model\dao\UserAccount;
use app\api\model\data\note\NoteData;
use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use think\Exception;
use think\Log;
use think\Validate;

class GetNoteAnswerList extends PageBase
{

    private $objNote;
    private $objNoteReply;
    private $objNoteReplyReply;
    private $objNoteReplyPraise;
    private $objUserAccount;
    private $objNoteData;

    public function __construct()
    {
        parent::__construct();

        $this->objNote = new Note();
        $this->objNoteReply = new NoteReply();
        $this->objUserAccount = new UserAccount();
        $this->objNoteReplyReply = new NoteReplyReply();
        $this->objNoteReplyPraise = new NoteReplyPraise();
        $this->objNoteData = new NoteData();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'note_id' => 'require',
        ];
        $msg = [
            'note_id.require' => '帖子id不能为空',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    /**
     * page 入口
     *
     * @param $param
     * @return array
     * @throws Exception
     */
    public function excute($param)
    {
        $this->checkToken($param);
        $this->user_id = !empty($this->user_id) ? $this->user_id : 0;

        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_PARAM, $ret);
        }

        // 2、从数据库中获取帖子详情
        $noteInfo = $this->getNoteInfoFromDB($param['note_id']);
        if (false === $noteInfo) {
            Log::error('get note info from db fail. [note_id: ' . $param['note_id'] . ']');
            return $this->getRes(Error::ERR_SYS);
        }

        if (empty($noteInfo)) {
            Log::alert('note info is empty. [note_id: ' . $param['note_id'] . ']');
            return $this->getRes(Error::ERR_NOTE_NOT_EXIST);
        }

        // 3、校验是否被删除
        if (Flag::CONST_NOTE_DELETED == $noteInfo['is_delete']) {
            return $this->getRes(Error::ERR_NOTE_DELETED);
        }

        $userid = [];
        $replyid = [];
        $user_account = [];
        $replyToreply = [];
        $replyid2Praise = [];
        $noteReplay = [];

        if (!empty($param['tab'])) {
            $replyreply_ret = $this->objNoteReplyReply->getHotList($param['note_id'], $this->offset, $this->limit);
            if (!empty($replyreply_ret)) {
                foreach ($replyreply_ret as $val) {
                    $replyid[] = $val['reply_id'];
                    $userid[] = $val['userid'];
                    $userid[] = $val['recv_userid'];
                }
            }
        }

        if (!empty($replyid)) {
            $conds = [
                'id' => ['in', $replyid]
            ];
            $noteReplay = $this->objNoteReply->getNoteReply($conds);
            if (empty($noteReplay)) {
                $noteReplay = [];
            }

            foreach ($noteReplay as $val) {
                $userid[] = $val['userid'];
            }
        } else {
            // 4、获取回复列表
            $noteReplay = $this->getNoteReplayFromDB($param['note_id']);
            if (empty($noteReplay)) {
                $noteReplay = [];
            }

            foreach ($noteReplay as $val) {
                $userid[] = $val['userid'];
                $replyid[] = $val['id'];
            }

            if (!empty($replyid)) {
                $conds = [
                    'note_id' => ['=', $param['note_id']],
                    'recv_userid' => ['=', $noteInfo['creator']],
                    'reply_id' => ['in', $replyid],
                ];
                $replyreply_ret = $this->objNoteReplyReply->getList($conds);
                if (!empty($replyreply_ret)) {
                    foreach ($replyreply_ret as $val) {
                        $replyToreply[$val['reply_id']][] = $val;
                        $userid[] = $val['userid'];
                        $userid[] = $val['recv_userid'];
                    }
                }
            }
        }

        if (!empty($replyid)) {
            $reply_praise_ret = $this->objNoteReplyPraise->getNoteReplyPraiseCount($param['note_id'], $replyid);
            if (!empty($reply_praise_ret)) {
                foreach ($reply_praise_ret as $val) {
                    $replyid2Praise[$val['reply_id']] = $val['cnt'];
                }
            }
        }

        if (!empty($userid)) {
            $userid = array_unique($userid);
            $user_ret = $this->objUserAccount->getUserAccountByUserids($userid);
            if (!empty($user_ret)) {
                $user_ret = $this->modelToArray($user_ret);
                foreach ($user_ret as $val) {
                    $user_account[$val['id']] = $val;
                }
            }
        }

        $this->data['list'] = $this->composeData($noteReplay, $user_account, $replyToreply, $replyid2Praise);
        return $this->getRes();
    }

    /**
     * 从数据库中获取帖子详情
     *
     * @param $cir_id
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getNoteInfoFromDB($note_id)
    {
        if (!$note_id) {
            return false;
        }
        $arrCond = [
            'id' => ['=', $note_id]
        ];
        $ret = $this->objNote->getNote($arrCond);
        if (false === $ret) {
            return false;
        }
        if (empty($ret)) {
            return [];
        }
        $ret = $ret[0];
        return $ret;
    }

    /**
     * 从数据库中获取帖子回复列表
     *
     * @param $cir_id
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getNoteReplayFromDB($note_id)
    {
        if (!$note_id) {
            return false;
        }
        $arrCond = [
            'note_id' => ['=', $note_id],
            'is_delete' => ['=', Flag::CONST_NOTEREPLAY_DELETE_NOT]
        ];
        $ret = $this->objNoteReply->getNoteReply($arrCond, [], $this->offset, $this->limit, ' create_time desc ');
        if (false === $ret) {
            return false;
        }
        if (empty($ret)) {
            return [];
        }
        return $ret;
    }

    public function composeData($note_replay, $user_account, $replyToreply, $replyid2Praise)
    {
        $data = [];
        $i = 1;
        foreach ($note_replay as $val) {
            $nickname = $user_account[$val['userid']] ? $user_account[$val['userid']]['nick_name'] : '';
            $photo = $user_account[$val['userid']] ? $user_account[$val['userid']]['avatar'] : '';
            $level = $user_account[$val['userid']] ? $user_account[$val['userid']]['level'] : 0;
            $sex = $user_account[$val['userid']] ? $user_account[$val['userid']]['sex'] : '1';
            $reply = [];
            $replyreply = !empty($replyToreply[$val['id']]) ? $replyToreply[$val['id']] : [];
            foreach ($replyreply as $val1) {
                if (empty($user_account[$val1['userid']]) || empty($user_account[$val1['recv_userid']])) {
                    continue;
                }
                $reply[] = [
                    'userid' => $val1['userid'],
                    'nickname' => $user_account[$val1['userid']]['nick_name'],
                    'content' => $val1['content']
                ];
            }

            $is_praise = 0;
            $conds = [];
            $conds['note_id'] = ['=', $val['note_id']];
            $conds['reply_id'] = ['=', $val['id']];
            $conds['userid'] = ['=', $this->user_id];
            $retCnt = $this->objNoteReplyPraise->getNoteReplyPraiseCountByConds($conds);
            if (!empty($retCnt)) {
                $is_praise = 1;
            }

            $data[] = [
                'reply_id' => $val['id'],
                'userid' => $val['userid'],
                'nickname' => $nickname,
                'level' => $level . '.LV',
                'sex' => $sex ? 'F' : 'M',
                'photo' => $photo,
                'floor' => $i . 'F',
                'content' => $val['content'],
                'time' => $this->objNoteData->caleDate($val['create_time']),
                'praise_count' => !empty($replyid2Praise[$val['id']]) ? $replyid2Praise[$val['id']] : 0,
                'reply' => $reply,
                'reply_cnt' => count($reply),
                'is_praise' => $is_praise,
            ];
            $i++;
        }
        return $data;
    }
}
